package com.ww.scm.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ww.core.orm.Page;
import com.ww.core.orm.PropertyFilter;
import com.ww.core.orm.PropertyFilter.MatchType;
import com.ww.scm.constants.Constants;
import com.ww.scm.entity.mat.Bill;
import com.ww.scm.entity.mat.TransactionDetail;
import com.ww.scm.service.StorageManager;
import com.ww.scm.valueObject.croe.ResponseEntity;
import com.ww.scm.valueObject.croe.ResponseInfo;
import com.ww.scm.valueObject.croe.ResponseJson;
import com.ww.scm.valueObject.mat.BillDetailVo;
import com.ww.scm.valueObject.mat.BillVo;

@Controller
@RequestMapping(value = "/purchase")
public class PurchaseController {
	
	/*
	 * 日志类
	 */
	private static Logger logger = LoggerFactory.getLogger(PurchaseController.class);

	@Autowired
	private StorageManager storageManager;
	
	public void setStorageManager(StorageManager storageManager) {
		this.storageManager = storageManager;
	}
	
	@RequestMapping(params = "method=list")
	@ResponseBody
	public String list(HttpServletRequest request) {
		String limit=request.getParameter("limit");
		String start=request.getParameter("start");

		Page<Bill> page = new Page<Bill>(start,limit);
		
		//查询条件可以有几种方式，看自己喜欢。
		//第一种
		//../../purchase.do?method=list&filter_EQS_sysFlag=1
		//List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		//第二种
		//../../purchase.do?method=list&sysFlag=1
		//String sysFlag=request.getParameter("sysFlag");
		//List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		//filters.add(new PropertyFilter(MatchType.EQ,"sysFlag",sysFlag));
		
		//更多查询方式可以看看StorageRepository.java->createOrUpdateStorage方法
		
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		filters.add(new PropertyFilter(MatchType.EQ,"sysFlag",Constants.SYS_FLAG_USEING));
		page = storageManager.findBill(page, filters);
		List<BillVo> returnList=new ArrayList<BillVo>();
		for (Bill bill : page.getResult()) {
			BillVo billVo=new BillVo(bill);
			returnList.add(billVo);
		}
		ResponseEntity<BillVo> responseEntity=new ResponseEntity<BillVo>();
		responseEntity.setEntity("billVo", returnList);
		responseEntity.setMaxRecordSizeValue(page.getTotalItems());
		return responseEntity.toJson();
	}
	
	@RequestMapping(params = "method=listDetail")
	@ResponseBody
	public String listDetail(String lastTransactionId) {
		
		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		filters.add(new PropertyFilter(MatchType.EQ,"transaction.id",lastTransactionId));
		filters.add(new PropertyFilter(MatchType.EQ,"sysFlag",Constants.SYS_FLAG_USEING));
		List<TransactionDetail>  transactionDetailList=storageManager.findTransactionDetailBy(filters);
		List<BillDetailVo> returnList=new ArrayList<BillDetailVo>();
		for (TransactionDetail billDetail : transactionDetailList) {
			BillDetailVo billDetailVo=new BillDetailVo(billDetail);
			returnList.add(billDetailVo);
		}
		ResponseEntity<BillDetailVo> responseEntity=new ResponseEntity<BillDetailVo>();
		responseEntity.setEntity("billDetailVo", returnList);
		responseEntity.setMaxRecordSizeValue(transactionDetailList.size());
		return responseEntity.toJson();
	}
	

    @RequestMapping(params = "method=delete")
    @ResponseBody
    public String delete(String ids) {
    	if (StringUtils.isBlank(ids)){
    		logger.error("删除方法中传入参数ids为空!");
    		ResponseInfo responseInfo=new ResponseInfo(false,"删除方法中传入参数ids为空!");
    		return responseInfo.toJson();
    	}
    	ResponseInfo responseInfo=new ResponseInfo();
    	//todo:这里需要得到登录用户
    	String operator="1001";
    	try {
    		String[] idArray=ids.split(Constants.SEPARATOR_COLON);
            for(int i = 0; i < idArray.length; i++) {
            	storageManager.deleteBill(idArray[i], operator);
            }
		} catch (Exception e) {
			logger.error("删除单据出错：",e);
			responseInfo.setResponseContent(e.getMessage());
			responseInfo.setResponseSuccess(false);
		}
		return responseInfo.toJson();
    }
    
    @RequestMapping(params = "method=edit")
    @ResponseBody
    public String edit(String id) {
    	if (StringUtils.isBlank(id)){
    		logger.error("修改方法中传入参数id为空!");
    		ResponseInfo responseInfo=new ResponseInfo(false,"修改方法中传入参数id为空!");
    		return responseInfo.toJson();
    	}
		Bill bill = storageManager.findBillById(id);
		BillVo billVo=new BillVo(bill);
		billVo.renderBillDetailVo(bill);
		ResponseEntity<BillVo> responseEntity=new ResponseEntity<BillVo>();
		responseEntity.setEntity("billVo", billVo);
        return responseEntity.toJson();
    }
    
    @RequestMapping(params = "method=save")
    @ResponseBody
    public String save(String dataset) {
    	ResponseInfo responseInfo=new ResponseInfo();
    	try {
    	ResponseJson<BillVo> responseJson=new ResponseJson<BillVo>(dataset);
    	BillVo billVo=responseJson.toEntity(BillVo.class, "billVo");
    	storageManager.saveBill(billVo);
    	} catch (Exception e) {
			logger.error("保存出错：",e);
			responseInfo.setResponseContent(e.getMessage());
			responseInfo.setResponseSuccess(false);
		}
    	return responseInfo.toJson();
    }
    
    @RequestMapping(params = "method=randomBillCode")
    @ResponseBody
    public String randomBillCode(String billType) {
    	String billCode=storageManager.randomBillCode(billType);
    	
		ResponseEntity<String> responseEntity=new ResponseEntity<String>();
		responseEntity.setEntity("billCode", billCode);
        return responseEntity.toJson();
    }
    
	
}
